package controller;

import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import adaptors.TabReference;

import tools.*;
import view.*;

public class Controller	{
	public TabLibrary tabLib = new TabLibrary();
	public Preferences prefs;
	private View view;
	
	private char oSFPS = '/'; // OS File Path Separator
	
	
	public Controller()	{
		String os = System.getProperty("os.name").toLowerCase();
		
		System.out.println("OS: " + os);
		
		if( os.contains("wind") )	{
			oSFPS = '\\';
		}
	}
		
	public void performInternetSearch(String text)	{ // When a user presses enter, the listener from view redirects to this method
		//Insert link to model
		TabQuery tq = new TabQuery();
		
		//fill the table in the view
		displayInternetSearchResults(tq.findTabs(text));
	}
	
	public void displayInternetSearchResults(ArrayList<Tab> allTabs)	{
		System.out.println("All tabs: " + allTabs.size());
		view.internetSearchResults(allTabs);	// Update view of internet search
	}

	public boolean addTabToLibrary(Tab t)	{
		if( t == null )	{
			System.err.println("Null tab!");
			return false;
		}
		
		if( saveTab(t) )	{	// can we save?
			if( tabLib.addTab(t) )	{	// Add an entry into our lib file
				if( TabIO.writeTabLibFile(prefs.getTabRootDirectory()+"tablib.tlb", tabLib) )	{
					view.updateLocalTabs();	// update view of local tab listing
					return true;
				}

				return false;
			}
		}

		return false;
	}
	
	public boolean saveTab(Tab t)	{
		if( TabIO.hasDirectory(prefs.getTabRootDirectory() + t.getBandName()) )
			System.out.println("Directory Found!");
		else	{
			System.out.print("Directory not found, creating...");
			if( TabIO.createDirectory(prefs.getTabRootDirectory() + t.getBandName()) )	{
				System.out.println("done.");
			}
			else	{
				System.out.println("failed!");
				return false;
			}
		}

		// TODO Make this configurable in the preferences
		String file = prefs.getTabRootDirectory() + t.getFilePath();

		if( TabIO.writeTabFile(file, t) )	{
			return true;
		}
		else	{
			return false;
		}
	}

	public void setView(View v)	{
		view = v;
	}

	public void loadFilesAndSettings() {
		if( TabIO.fileExists(Preferences.preferencesFile) )	{
			prefs = Preferences.readPrefsFile(Preferences.preferencesFile);
			System.out.println("Preferences File Found!");
		}
		else	{
			prefs = new Preferences();
			System.out.println("Creating New Preferences File...");

			try {
				File f = new File("");
				prefs.setTabRootDirectory(f.getCanonicalPath()+oSFPS+"tabs"+oSFPS);
				System.out.println("Tab Root Directory Set To: " + prefs.getTabRootDirectory());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println("Setting Default Column Widths...");
			System.out.println("New Preferences File Created!");
			
			System.out.println("Setting Default Font Face...");
			prefs.setPreferredFont(new Font(Font.MONOSPACED, Font.BOLD, 12));
			
			prefs.save();
		}
		
		// Create tabs directory if it doesn't exist
		System.out.println("Looking for tab dir: " + prefs.getTabRootDirectory() );
		if( !TabIO.hasDirectory(prefs.getTabRootDirectory()) )
			if( !TabIO.createDirectory(prefs.getTabRootDirectory()) )
				System.out.println("Can't create the tabs directory, you're fucked!");

		// Load TabLib file with info about our tab collection
		if( TabIO.fileExists(prefs.getTabRootDirectory()+TabIO.TABLIB_FILE) )
			tabLib = TabIO.readTabLibFile(prefs.getTabRootDirectory()+TabIO.TABLIB_FILE);
		else
			tabLib = new TabLibrary();		

	}

	public boolean deleteTabFromLibrary(TabReference selectedTab) {
		if( tabLib.removeTab(selectedTab) )	{
			File f = new File(prefs.getTabRootDirectory()+selectedTab.getPath());
			f.delete();

			TreeMap<String, TabReference> tr = tabLib.findBand(selectedTab.getBandName().toLowerCase());
			
			if( tr.isEmpty() )	{
				File folder = new File(prefs.getTabRootDirectory()+selectedTab.getBandName());
				folder.delete();
				tabLib.removeBand(selectedTab.getBandName().toLowerCase());
			}
				
			TabIO.writeTabLibFile(prefs.getTabRootDirectory()+TabIO.TABLIB_FILE, tabLib);
			view.updateLocalTabs();
			return true;
		}
		
		return false;
	}
	
	public Preferences getPrefs()	{
		return prefs;
	}

	public void saveColumnWidths(int[] widths) {
		prefs.setSearchColumnWidths(widths);
	}

	public void savePreferences() {
		prefs.save();
		System.out.println("Prefs Saved!");
	}

	public void saveLocalTabSplitPosition(int current) {
		prefs.setLocalTabSplitPosition(current);
	}
}
